<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function Node(val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
        var a = new Node(1)
        var b = new Node(null)
        var c = new Node(2)
        var d = new Node(3)
        var e = new Node(4)
        var f = new Node(5)
        var g = new Node(5)
        a.left = b
        a.right = c
        b.left = d
        b.right = e
        c.left = f
        c.right = g
        // 路径总和3就是，不需要从根节点开始，随便从哪个节点开始都可以,只要找到和为目标值的就可以
        var pathSum = (root, targetSum) => {
            if (!root) {
                return false
            }
            debugger
            function traverse (cur, count) {
                debugger
                let result = 0
                // 注意判断叶子节点的办法
                if (!cur.left && !cur.right && count === 0) {
                    result++
                    return result // 叶子节点找到路径
                }
                if (!cur.left && !cur.right) return // 叶子结点没有找到路径

                if(cur.left) {
                    traverse(cur.left, count - cur.left.val)
                }

                if (cur.right) {
                    traverse(cur.right, count - cur.right.val)
                }
                return result
            }

            let rootNum = traverse(root, targetSum - root.val)
            let leftNum = traverse(root.left, targetSum - root.left)
            let rightNum = traverse(root.right, targetSum - root.right)
            return rootNum + leftNum + rightNum
        } 

        
        console.log(pathSum(a, 8));
    </script>
</body>

</html>